import {getIcons, nodeColors, fittingString, uuid} from '@/modules/topology/utils';

export const findById = (id, treeData) => {
  if (!treeData) return;
  // 深度优先查找
  const { children } = treeData;

  if (treeData.id === id) {
    return treeData;
  } else if (children && children.length) {
    for (let i = 0; i < children.length; i++) {
      if (children[i].id === id) {
        return children[i];
      } else {
        const nodes = findById(id, children[i]);

        if (nodes) {
          return nodes;
        }
      }
    }
  }
}

export const formatRelationData = (cm_unid, listData, associateType, level) => {
  let nodes = [];
  listData.map(item => {
    let obj = setNode(cm_unid, item, associateType, level);
    nodes.push(obj);
  })
  return nodes;
}

export const formatResourceData = (listData, level, moduleList) => {
  let nodes = [];
  listData.map(item => {
    const module = moduleList?.find(v => v.cmModuleId == item.cm_module_id);
    let obj = {
      ...item,
      key: item.cm_unid,
      id: item.cm_unid + uuid(),
      name: item.cm_name,
      cmModuleId: item.cm_module_id,
      moduleCode: module?.moduleCode,
      moduleName: module?.moduleName,
      moduleIcon: getIcons(module?.moduleIcon),
      children: null,
      level:  Number(level) + Number(1),
    };
    nodes.push(obj);
  })
  return nodes;
}

const setNode = (cm_unid, node, associateType, level) => {
  const {moduleRelations, srcInfo, destInfo} = node;
  const resource = cm_unid == srcInfo.resource.cm_unid ? destInfo.resource : srcInfo.resource;
  const definition = cm_unid == srcInfo.resource.cm_unid ? destInfo.moduleDefinition.definition : srcInfo.moduleDefinition.definition;
  const associateData = associateType[moduleRelations.associateType] || moduleRelations.associateType;

  let leafNode = {
    key: resource.cm_unid,
    id: resource.cm_unid + uuid(),
    name: resource.cm_name,
    cmModuleId: definition.cmModuleId,
    moduleCode: definition.moduleCode,
    moduleName: definition.moduleName,
    moduleIcon: getIcons(definition.moduleIcon),
    // resource,
    // definition,
    associate: associateData,
    children: null,
    level:  Number(level) + Number(1),
  };
  return  leafNode;
}

const moduleIcons = {
  'biz': "icon-yewu",
  'set': "icon-fuwuqijiqun",
  'service': "icon-fuwu",
};

export const arrayTreeAddLevel = (array) => {
    if (!Array.isArray(array)) return []
    const recursive = (array, level = 0) => {
        level++;
        return array.map(v => {
            v.key = v.instanceId,
            v.id = v.instanceId,
            v.name = v.instanceName;
            v.level = level;
            v.moduleIcon = getIcons(moduleIcons[v.moduleCode]);
            v.isBiz = true;
            const child = v.children;
            if (child && child.length) recursive(child, level);
            return v;
        })
    }
    return recursive(array)
}
